package com.egglazy.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.egglazy.Dto.UserAddDto;
import com.egglazy.Entity.User;
import com.egglazy.Service.UserService;
import com.egglazy.Utils.Result;
import com.egglazy.Utils.ResultUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;


@Tag(name = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @Operation(summary = "用户登录")
    @GetMapping("/login")
    public Result<User> login(@RequestParam("username") String username,
                              @RequestParam("password") String password) {
        User loginUser = userService.login(username, password);
        if (loginUser != null) {
            return ResultUtil.success(loginUser);
        } else {
            return ResultUtil.fail("用户名或密码错误!");
        }
    }

    @Operation(summary = "用户新增")
    @PostMapping("/addUser")
    public Result<String> register(@RequestBody UserAddDto userAddDto) {
        User user = new User();
        BeanUtils.copyProperties(userAddDto, user);
        user.setStatus(1);
        return userService.register(user);
    }

    @Operation(summary = "获取用户列表")
    @GetMapping("/getList")
    public Result<Page<User>> getUserList(@RequestParam("pageIndex") int pageIndex,
                                          @RequestParam("pageSize") int pageSize) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getStatus,1);
        Page<User> page = userService.page(new Page<>(pageIndex, pageSize), wrapper);
        return ResultUtil.success(page);
    }

    @Operation(summary = "根据用户id删除用户信息")
    @GetMapping("/deleteUserById")
    public Result<User> deleteUserById(@RequestParam("id") String id) {
        return userService.removeById(id) ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败！");
    }

    @Operation(summary = "根据用户id更新用户信息")
    @PostMapping("/updateUserById/{id}")
    public Result<String> updateUserById(@RequestBody UserAddDto userAddDto,
                                         @PathVariable("id") String id) {
        User user = new User();
        BeanUtils.copyProperties(userAddDto, user);
        user.setId(id);
        return userService.updateById(user) ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败！");
    }


    @Operation(summary = "根据用户id查询用户信息")
    @GetMapping("/getUserById")
    public Result<User> getUserById(@RequestParam("id") String id) {
        User byId = userService.getById(id);
        return ResultUtil.success(byId);
    }

}